<template>
  <uni-popup ref="popup" background-color="#fff" >
		
		
    <view class="modal-container">
      <view class="modal-header">
        <text class="modal-title">{{ title || '选择工序' }}</text>
				<uni-icons type="close" @click="closeModal" size='26'></uni-icons>
      </view>
      
      <view class="modal-body">
        <!-- 全选控制 -->
				<view class="select-all">
				  <checkbox
				    :checked="isAllSelected" 
				    @click="toggleAllSelection"
				  /> 全选
				</view>
        
        <!-- 工序列表 -->
        <view class="process-list">
          <checkbox-group @change="onChange">
            <view class="process-item" v-for="process in processes" :key="process.linkId">
              <checkbox :value="process.linkId" :checked="process.isChecked">
                <text slot="label">{{ process.linkName }}</text>
              </checkbox>
            </view>
          </checkbox-group>
        </view>
      </view>
      
      <view class="modal-footer">
        <button type="primary" @click="confirmSelection">确认</button>
      </view>
    </view>
  </uni-popup>
</template>

<script>
import request from '/utils/request.js';

export default {
  name: 'ProcessSelector',
  props: {
    // 弹窗标题
    title: {
      type: String,
      default: '选择工序'
    },
    // 初始选中的工序ID数组
    selectedItems: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      // 选中的工序ID数组（组件内部状态）
      selectedProcessItems: [],
      selectedProcessIds: [],
      // 全选状态
      isAllSelected: false,
			processes: [
				// { linkId: 1, linkName: '毛坯准备', isChecked: false },
				// { linkId: 2, linkName: '拉去江西', isChecked: false },
				// { linkId: 3, linkName: '品检', isChecked: false },
			]
    }
  },
	
  watch: {
    // 监听外部传入的选中状态变化
    selectedItems: {
      handler(newVal) {
        // this.selectedProcessItems = [...newVal];
        this.selectedProcessItems = [...newVal];
				this.selectedProcessIds = this.selectedProcessItems.map(p => p.linkId)
				
				if (this.selectedProcessIds.length < this.processes.length ) {
					this.isAllSelected = false
				} else if (this.selectedProcessIds.length == this.processes.length) {
					this.isAllSelected = true
				}
        // this.updateAllSelectionStatus();
      },
      immediate: true
    },
    
    // 监听内部选中状态变化
    selectedProcessItems: {
      handler() {
        // this.updateAllSelectionStatus();
      },
      deep: true
    }
  },
	mounted() {
		uni.showLoading({
	    title: '加载中...',
	    mask: true
	  });
	  request.get('/system/link/allList').then(res => { //加载工序列表
	    uni.hideLoading();
	    if (res.code === 200) {
	      this.processes = res.data.map(v => {
	        return {
	          ...v,
						linkId: v.id,
	          isChecked: false
	        }
	      });
	    }
	  })
	},
  methods: {
    // 显示弹窗
    open() {
      this.$nextTick(() => {
				this.processes.map(item => {
					item.isChecked = false;
					if (this.selectedProcessIds.includes(item.linkId)) {
						item.isChecked = true;
					}
				})
				if (this.selectedProcessIds.length < this.processes.length ) {
					this.isAllSelected = false
				}
        this.$refs.popup.open();
      });
    },
    
    // 关闭弹窗
    closeModal() {
      this.$refs.popup.close();
      // 触发关闭事件
      this.$emit('close');
    },
    onChange(event) {
			let arr = [...event.detail.value]
			this.selectedProcessItems = [];
			this.selectedProcessItems = this.processes.filter(p => {
				p.isChecked = false
				let linkId = p.linkId+''
				if (arr.includes(linkId)) {
					p.isChecked = true
					return {linkId:p.linkId, linkName: p.linkName, days: 0};
				}
			})
		},
    // 切换全选状态
    toggleAllSelection() {
      this.isAllSelected = !this.isAllSelected;
      
      if (this.isAllSelected) {
        // 全选
        this.selectedProcessItems = this.processes.map(process => {
					process.isChecked = true;
					return {linkId:process.linkId, linkName: process.linkName, days: 0};
				});
      } else {
        // 取消全选
				this.processes.map(process => {
					process.isChecked = false;
				});
        this.selectedProcessItems = [];
      }
      // let ids = this.selectedProcessItems.forEach(i => i.linkId);
      // 触发选中状态变化事件
			// console.log(ids, 'ids')
      // this.$emit('selectionChange', ids);
    },
    
    // 更新全选状态
    // updateAllSelectionStatus() {
    //   this.isAllSelected = this.selectedProcessItems.length === this.processes.length;
    // },
    
    // 确认选择
    confirmSelection() {
      this.closeModal();
      // 触发确认事件，传递选中的工序ID
			console.log(this.selectedProcessItems, '---111')
      this.$emit('confirm', this.selectedProcessItems);
    }
  }
}
</script>

<style lang="scss" scoped>
/* 弹窗样式 */
.modal-container {
  width: 80vw;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
}

.modal-body {
  padding: 15px;
  max-height: 300px;
  overflow-y: auto;
}

.select-all {
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}

.process-list {
  .process-item {
    padding: 8px 0;
  }
}

.modal-footer {
  padding: 15px;
  justify-content: flex-end;
}
</style>    